package com.smart.mq.controller;

import com.smart.mq.entity.User;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class ExampleController {
    @Resource
    RocketMQTemplate template;
    /**
     * 异步普通消息
     * 异步延迟消息
     * 同步顺序消息
     */
    /**
     * destination
     *
     * @return
     */
    @GetMapping("/msg")
    public String sendMsg(String msg) {
        // 发送短信   手机号
        template.syncSend("test-msg", msg);
        return "发送消息";
    }

    /**
     * 异步消息
     * 1. 异步普通消息
     *
     * @param msg
     * @return
     */
    @GetMapping("/async")
    public String sendAsyncMsg(String msg) {
        /**
         *       destination – 主题
         *       message – 需要发送的数据
         *       sendCallback – 发送是否成功的回调
         *      timeout –  发送消息超时的时间  单位毫秒
         *      delayLevel – 延迟消息 级别
         */
        User user = new User();
        user.setUid("1");
        user.setUsername("世界曹县");
        /**
         * 发送普通的异步消息
         */
        template.asyncSend("test-async-msg", user, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
                    log.info("发送消息成功");
                }
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });

        return "发送消息";
    }

    /**
     * 发送延迟消息
     * 订单自动取消
     *
     * @param msg
     * @return
     */
    @GetMapping("/async/delay")
    public String sendAsyncDelayMsg(String msg) {
        //  18 个级别   1 - 18
        GenericMessage<String> message = new GenericMessage<>("延迟消息");
        template.asyncSend("test-delay-msg", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        }, -1, 18);
        return "发送消息";
    }

    /**
     * 同步顺序消息
     *
     * @param msg
     * @return
     */
    @GetMapping("/sync/orderly")
    public String sendSyncOrderlyMsg(String msg) {
        /**
         * 发送顺序消息
         */
        template.syncSendOrderly("test-sync-orderly-msg", msg, "1");
        return "发送消息";
    }


}
